package com.rr.config;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.StripPrefixGatewayFilterFactory;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author RR
 * @date 2023/1/18 17:36
 */
@Component
public class DiyAddHeaderGatewayFilterFactory extends AbstractGatewayFilterFactory<DiyAddHeaderGatewayFilterFactory.Config> {


    public DiyAddHeaderGatewayFilterFactory() {
        super(DiyAddHeaderGatewayFilterFactory.Config.class);
    }

    public List<String> shortcutFieldOrder() {
        return Arrays.asList("headerKey", "headerValue");
    }

    public GatewayFilter apply(DiyAddHeaderGatewayFilterFactory.Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                HttpHeaders headers = exchange.getResponse().getHeaders();
                headers.add(config.getHeaderKey(), config.getHeaderValue());
                return chain.filter(exchange);
            }
        };
    }

    public static class Config {
        private String headerKey;
        private String headerValue;

        public Config() {
        }

        public String getHeaderKey() {
            return headerKey;
        }

        public void setHeaderKey(String headerKey) {
            this.headerKey = headerKey;
        }

        public String getHeaderValue() {
            return headerValue;
        }

        public void setHeaderValue(String headerValue) {
            this.headerValue = headerValue;
        }
    }
}

